// pages/cart/cart.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart_list: [],
    totalPrice: 0,
    startX: 0, //开始坐标
    startY: 0
  },
  goIndex() {
    wx.switchTab({
      url: "../categories/categories"
    })
  },


  touchstart: function (e) {
    this.data.cart_list.map(item => {
      if (item.isTouchMove) {
        item.isTouchMove = false;
      }
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cart_list: this.data.cart_list
    })
  },
  //滑动事件处理
  touchmove(e) {
    var
      index = e.currentTarget.dataset.index, //当前索引
      startX = this.data.startX, //开始X坐标
      startY = this.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = this.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    this.data.cart_list.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    this.setData({
      cart_list: this.data.cart_list
    })
  },
  angle(start, end) {
    var X = end.X - start.X,
      Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(Y / X) / (2 * Math.PI);
  },
  delCartItem(e) {
    var that=this;
    const index=e.currentTarget.dataset.index;
    console.log(index);
    wx.request({
      url: app.globalData.url +'/index.php?s=api/cart/delete',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'get',
        data: {token:app.globalData.token,item_sku_id:index,app_id:10001},
        success: (res) => {
          if (res.data.code == 1) {
          that.onShow();
        }else{
          that.setData({
            cart_list:''
          });
        }
         
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    app.getUserToken(function (err, token) {
    wx.request({
      url: app.globalData.url +'/index.php?s=api/cart/lists',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'get',
        data: {token:app.globalData.token,app_id:10001},
        success: (res) => {
          if (res.data.code == 1) {
          that.setData({
            cart_list:res.data.data.goods_list,
            totalPrice:res.data.data.order_total_price
          });
        }else{
          that.setData({
            cart_list:''
          });
        }
         
        }
      })
    })
  },
  checkOut:function(){
    wx.navigateTo({
      url: '../payment/payment',
    })
  },

  onShareAppMessage: function () {

  }
})